﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NetC100K;
using NetC100K.Setting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace NetC100KHost
{
    internal class HostService : IHostedService
    {
        private ILogger _logger;
        private ServerPool _service;
        private IConfiguration _configuration;

        public HostService(ServerPool service, IConfiguration configuration, ILogger<HostService> logger)
        {
            _service = service;
            _logger = logger;
            _configuration = configuration;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                var serverSetting = _configuration.GetSection("Server").Get<ServerSetting>();
                if (serverSetting == null) throw new ArgumentNullException("配置文件server配置为空");

                var filters = _configuration.GetSection("Filters").Get<string[]>();

                return _service.Start(serverSetting, filters);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "服务开启时发生错误：{0}", ex.Message);
            }
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            try
            {
                if (_service != null && cancellationToken.IsCancellationRequested)
                {
                    return _service.Close();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "HostService关闭时发生错误：{0}", ex.Message);
            }
            return Task.CompletedTask;
        }
    }
}